package com.weilive.core.utils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class HMACSHA1Utils {

	private static final String MAC_NAME = "HmacSHA1";
	private static final String ENCODING = "UTF-8";

	public static void main(String[] args) throws Exception {
		String key = "f85b8b30f73eb2bf5d8063a9224b5e90";
		String toHash = "GET" + "\n" + "Thu, 09 Aug 2012 13:33:46 +0000" + "\n" + "/ApiChannel/Report.m";
		// String toHashUtf8 = URLEncoder.encode(toHash, "UTF-8");
		String res = hmacSha1(toHash, key);
		// System.out.print(res+"\n");

		System.out.println(res);

		
		String res1 = hmacSHA1Encrypt(toHash, key);
		// System.out.print(res+"\n");

		System.out.println(res1);

		// String signature;
		// try {
		// signature = new String(Base64UrlSafe.encodeBase64(res.getBytes()),
		// "UTF-8");
		// signature = appendEqualSign(signature);
		// System.out.print(signature);
		// } catch (UnsupportedEncodingException e) {
		// e.printStackTrace();
		// }
	}

	public static String hmacSha1(String value, String key) {
		try {
			// Get an hmac_sha1 key from the raw key bytes
			byte[] keyBytes = key.getBytes();
			SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

			// Get an hmac_sha1 Mac instance and initialize with the signing key
			Mac mac = Mac.getInstance("HmacSHA1");
			mac.init(signingKey);

			// Compute the hmac on input data bytes
			byte[] rawHmac = mac.doFinal(value.getBytes());

			// Convert raw bytes to Hex
			String hexBytes = byte2hex(rawHmac);
			return hexBytes;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
	 * 
	 * @param encryptText
	 *            被签名的字符串
	 * @param encryptKey
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static String hmacSHA1Encrypt(String encryptText, String encryptKey) {

		try {
			byte[] data = encryptKey.getBytes(ENCODING);
			// 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
			SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
			// 生成一个指定 Mac 算法 的 Mac 对象
			Mac mac = Mac.getInstance(MAC_NAME);
			// 用给定密钥初始化 Mac 对象
			mac.init(secretKey);

			byte[] text = encryptText.getBytes(ENCODING);
			// 完成 Mac 操作
			return HexStringUtils.encrypt(mac.doFinal(text));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String byte2hex(final byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0xFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs;
	}

	private static String appendEqualSign(String s) {
		int len = s.length();
		int appendNum = 8 - (int) (len / 8);
		for (int n = 0; n < appendNum; n++) {
			s += "%3D";
		}
		return s;
	}
}